package com.rwlai.dianshang.service;

import com.rwlai.dianshang.domain.Order;
import com.rwlai.dianshang.domain.OrderItem;
import com.rwlai.dianshang.domain.Product;
import com.rwlai.dianshang.domain.User;
import com.rwlai.dianshang.repository.OrderRepository;
import com.rwlai.dianshang.repository.ProductRepository;
import com.rwlai.dianshang.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by liutim on 2017/11/28.
 */
@Service
@Transactional
public class ShangchengServicecImpl implements ShangchengService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public User addUser(User u) {
        return this.userRepository.save(u);
    }

    @Override
    public Order placeOrder(Order order, User u) {
        order.setUserid(u.getId());

        order=this.orderRepository.save(order);
        for(OrderItem item:order.getItems().get()){
            changeProductStock(item.getProduct().getId(),-item.getCount());
        }

        return order;
    }

    @Override
    public Product addProduct(Product p) {
        return this.productRepository.save(p);
    }

    @Override
    public void changeProductStock(String productid, int delta) {
        Product p=this.productRepository.findOne(productid);
        p.changeStockByDelta(delta);
        this.productRepository.save(p);
    }

    @Override
    public Order getOrderById(String id) {
        return this.orderRepository.findOne(id);
    }


}
